var http = require('http');
var express = require('express');
var socket = require('socket.io');
var path = require('path');
var app = express();
var controllers = require('./controllers');
var bodyParser = require('body-parser');
var async = require('async');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var MongoStore =  require('connect-mongo')(session);

var eventApi = require('./services/eventApi');
var socketApi = require('./services/socketApi');

var signedCookieParser = cookieParser('mychat');
var sessionStore = new MongoStore({
  url:'mongodb://localhost/mychat'
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(cookieParser());
app.use(session({
  secret:'mychat',
  resave:true,
  saveUninitialized:true,
  cookie:{
    maxAge:6*1000,
  },
  store:sessionStore
}));
if ('development' == app.get('env')) {
    console.log('development');
  app.set('staticPath', '/static')
} else {
  console.log('production');
  app.set('staticPath', '/build')
}

app.use(express.static(__dirname + app.get('staticPath')));

var server = http.createServer(app);
server.listen(3000);
server.on('listening',function(){
	console.log('running on port 3000');
});

app.get('/api/validate',eventApi.validate);
app.post('/api/login',eventApi.login);
app.get('/api/logout',eventApi.logout);


app.use(function(req,res){
  res.sendFile(path.join(__dirname, app.get('staticPath') + '/index.html'))
});


var io = require('socket.io').listen(server);
//接口认证
io.set('authorization',function(handshakeData,accept){
  signedCookieParser(handshakeData,{},function(err){
    if(err){
      accept(err,false);
    }else{
      sessionStore.get(handshakeData.signedCookies['connect.sid'],function(err,session){
        if(err){
          accept(err.message,false);
        }else{
          handshakeData.session = session;
          if(session&&session._userid){
            accept(null,true);
          }else{
            accept('no login');
          }
        }
      });
    }
  }); 
});

io.sockets.on('connection', function(socket) {
  console.log('ready');
  socketApi.connect(socket);
  socket.on('disconnect',function(){
    socketApi.disconnect(socket);
  });
  socket.emit('connected','123');
  socket.on('mychat',function(request){
    console.log(request.action);
    console.log(request.params);
    socketApi[request.action](request.params,socket,io);
  });
/*  //创建一个新的房间
  socket.on('createRoom',function(roomName){
    console.log(roomName);
    controllers.Room.saveRoom(roomName,function(err,room){
      if(err){
        socket.emit('err',{
          msg:err,
        });
        console.log(err);
      }else{
          io.sockets.emit('addRoom',room);
      }
    });
  });*/
  //获取所有的房间以及相关信息
/*  socket.on('getAllRooms',function(){
    controllers.Room.findRoomById(function(err,roomsData){
      socket.emit('roomsData',roomsData);
    });
  });
  socket.on('getRoomById',function(_roomId){
     controllers.Room.getRoomDataByRoomId(_roomId,function(err,roomsData){
      socket.emit('roomData.'+_roomId,roomsData);
    });
  });
  socket.on('joinRoom',function(roomData){
    console.log('server joinRoom');
    controllers.User.joinRoom(roomData,function(err){
      if(err){
        socket.emit('err',{
          msg:err,
        });
      }else{
        socket.join(roomData.room._id);
        socket.emit('joinRoom.'+roomData.user._id,roomData);
      }
      io.sockets.in(roomData.room._id).emit('joinRoom',roomData);
    });
  }); 
  //获取消息
  socket.on('getRoom', function() {
    async.parallel({
      'getOnlineUser':function(callback){
        controllers.User.getOnlineUser(callback);
      },
      'getMessages':function(callback){
        controllers.Message.getMessages(callback);
      }
    },function(err,results){
      console.log('err'+err);
      if(err){
        socket.emit('err',{
          msg:err
        })
      }else{
        socket.emit('roomData',{
          users:results.getOnlineUser,
          messages:results.getMessages,
        });

      }
    });
  	controllers.Message.getMessages(function(err,messages){
  		if(err){
  			socket.emit('err', {
  				msg:err
  			});
  		}else{
  			socket.emit('messages.read',messages);
  		}
  	})
  })
  socket.on('messages.create', function(message) {
    console.log('create a message');
  	controllers.Message.saveMessage(message,function(err,message){
      console.log(message.toString());
  		if(err){
        console.log('error'+err.toString());
  			socket.emit('err', {
  				msg:err,
  			});
  		}else{
        console.log('server addmsg');
  			io.sockets.in(message.muser._roomId).emit('messages.add', message);
  		}
  	});
  });
  //用户离开某一个房间
  socket.on('leaveRoom',function(leave){
    controllers.User.leaveRoom(leave,function(err){
      if(err){
        socket.emit('err',{
          msg:err
        });
      }else{
        socket.leave(leave._roomId);
        console.log('leave room');
        io.sockets.emit('leaveRoom',leave);
      }
    });
  });
  //断开连接
  socket.on('disconnect',function(){
    console.log('disconnect');
    //用户下线
    controllers.User.offline(socket.request.session._userid,function(err,user){
      if(err){
        socket.emit('err',{
          msg:err,
        })
      }else{
        if(user._roomId){
          socket.broadcast.emit('removeUser',user);
          controllers.User.leaveRoom({
          _id:user._id
        },function(){});
        }

        
      }
    });
    
    //减少连接数，并向所有客户端广播
    --connectionCount;
    socket.broadcast.emit('connectionCount',connectionCount);
    //广播退出消息
    socket.broadcast.emit('messages.add',{
      mcontent:'用户'+socket.request.session.username+'退出聊天室',
      mtime:Date.now(),
      muser:{
        'name':'SYSTEM',
      }
    });
  });*/

});